/**
 *
 */
package com.mc.mcgoweb.filter;

import com.alibaba.fastjson.JSONObject;
import com.mc.common.base.BaseResponse;
import com.mc.common.cookie.CookieConstant;
import com.mc.common.cookie.CookieUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 过滤器,用户设置允许跨域请求
 */
@WebFilter(filterName = "loginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(LoginFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setHeader("Access-Control-Allow-Methods", "*");
        res.setHeader("Access-Control-Max-Age", "3600");
        res.setHeader("Access-Control-Allow-Headers", "Content-Type,access_token");
        res.setHeader("Content-type", "text/html;charset=UTF-8");
        res.setCharacterEncoding("UTF-8");

        String servletPath = req.getServletPath();

        //错误页面,登录页面,sso的回调地址,不在过滤范围
        if (servletPath.contains("/login")) {
            chain.doFilter(request, res);
            return;
        }

        String header = req.getHeader(CookieConstant.ACCESS_TOKEN);
        Cookie cookie = CookieUtil.get(req, header);

        //请求头信息未携带token
        if (StringUtils.isEmpty(header)||cookie==null) {
            BaseResponse baseResponse = new BaseResponse();
            baseResponse.setSuccess(false);
            baseResponse.setCode("400");
            baseResponse.setMessage("未登录");
            res.setCharacterEncoding("UTF-8");
            res.getWriter().write(JSONObject.toJSONString(baseResponse));
            return;
        }

        chain.doFilter(request, res);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

    @Override
    public void destroy() {
    }
}
